/**
 * 实体ID类型
 */
export type EntityId = string

/**
 * 实体接口
 */
export interface Entity<T> {
  id: EntityId
  value: T
}

/**
 * 弱引用实体接口
 */
export interface WeakEntity<T> {
  id: EntityId
  getValue(): T | null
}

/**
 * 实体映射类，管理实体的创建、更新和访问
 */
export class EntityMap {
  private entities = new Map<EntityId, any>()
  private nextId = 1

  /**
   * 创建新实体
   */
  create<T>(value: T): Entity<T> {
    const id = this.nextId.toString()
    this.nextId++
    
    const entity: Entity<T> = {
      id,
      value
    }
    
    this.entities.set(id, entity)
    return entity
  }

  /**
   * 获取实体
   */
  get<T>(id: EntityId): Entity<T> | undefined {
    return this.entities.get(id)
  }

  /**
   * 更新实体值
   */
  update<T>(id: EntityId, newValue: T): void {
    const entity = this.entities.get(id)
    if (entity) {
      entity.value = newValue
    }
  }

  /**
   * 删除实体
   */
  delete(id: EntityId): void {
    this.entities.delete(id)
  }

  /**
   * 创建弱引用实体
   */
  createWeak<T>(value: T): WeakEntity<T> {
    const entity = this.create(value)
    
    return {
      id: entity.id,
      getValue: (): T | null => {
        const e = this.get<T>(entity.id)
        return e ? e.value : null
      }
    }
  }
}